package cn.cdeden.knowledge.controller.analysis;


import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.oss.util.FileProcessingUtil;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.controller.online.search.SearchFilesInfoFactory;
import cn.cdeden.knowledge.domain.dto.FileFormatSuffixDto;
import cn.cdeden.knowledge.domain.dto.FilesTree;
import cn.cdeden.knowledge.domain.dto.PortalQueryParam;
import cn.cdeden.knowledge.domain.vo.FileAnalysisDataVo;
import cn.cdeden.knowledge.utils.DateUtil;
import cn.cdeden.knowledge.utils.FileUtil;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.domain.vo.RemoteUserVo;
import cn.cdeden.system.api.model.LoginUser;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;

/**
 * 文件:文件库文件的分类分析
 */
@Slf4j
@RestController
@RequiredArgsConstructor
//@Api(tags = "文件:文件库文件的分类分析")
@RequestMapping("/api/analysis")
public class FileAnalysisController {

    private final SearchFilesInfoFactory searchFilesInfoFactory;

    @DubboReference(check = false)
    private final RemoteUserService remoteUserService;


    /**
     * 文件:文件库文件的查询
     * @param query
     * @param pageable
     * @return
     */
    @GetMapping("/file/query")
//    @Log("文件:文件库文件的查询")
//    @ApiOperation("文件:文件库文件的查询")
    public R queryAllFiles(@Validated PortalQueryParam query, Pageable pageable) {
        //参数验证
        validation(query);
        TableDataInfo<FilesTree> info = searchFilesInfoFactory.queryNodeFileInfoPage(query, LoginHelper.getLoginUser(), pageable);
//        TableDataInfo<FilesTree> info = searchFilesInfoFactory.queryNodeFileInfoPage(query, FileUserUtils.getUser(), pageable);
        info.getRows().forEach(info01 ->
        {
            info01.setCreatorName(info01.getCreateId());
            String superiorsPath = info01.getSuperiorsPath().startsWith("/") ?
                info01.getSuperiorsPath().substring(1) : info01.getSuperiorsPath();
            info01.setSuperiorsPath(superiorsPath);
        });
//        info.getContent().forEach(info01 ->
//        {
//            info01.setCreatorName(info01.getCreateId());
//            String superiorsPath = info01.getSuperiorsPath().startsWith("/") ?
//                info01.getSuperiorsPath().substring(1) : info01.getSuperiorsPath();
//            info01.setSuperiorsPath(superiorsPath);
//        });
        return R.ok(info);
    }


    /**
     * 文件:文件库文件的查询导出
     * @param query
     * @param response
     */
    @GetMapping("/file/export")
//    @Log("文件:文件库文件的查询导出")
//    @ApiOperation("文件:文件库文件的查询导出")
    public void fileExport(@Validated PortalQueryParam query, HttpServletResponse response) {
        LoginUser user = LoginHelper.getLoginUser();
//        FileUserDto user = FileUserUtils.getUser();
        List<FilesTree> filesTrees = searchFilesInfoFactory.queryNodeFileInfo(query, user);
        if (ObjectUtil.isEmpty(filesTrees)) {
            throw new RuntimeException("暂无数据可以导出");
        }

        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < filesTrees.size(); i++) {
            FilesTree info = filesTrees.get(i);
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("序号", (i + 1));
            //判断父级路径 第一个字符串是否是 / 如果是者删除这个/ 不是就不管
            String superiorsPath = info.getSuperiorsPath().startsWith("/") ?
                info.getSuperiorsPath().substring(1) : info.getSuperiorsPath();
            map.put("文件路径", superiorsPath);
            map.put("文件名称", info.getRealName() + (StringUtils.isNotBlank(info.getSuffix()) ? "." + info.getSuffix() : ""));
            map.put("文件大小", FileUtil.getSizeUnit(info.getSize()));

//            log.info("文件编号" + info + "createId:" + );
            String createId = info.getCreateId();
            String nickName = "无法找到人员";
            if (StringUtils.isNotBlank(createId)) {
                RemoteUserVo userInfo = remoteUserService.selectUserByUserId(Long.getLong(createId));
//                UserVo userInfo = userService.getUserInfo(createId);
                nickName = ObjectUtils.isNotEmpty(userInfo) ? userInfo.getNickName() : "无法找到人员";
            }
            map.put("作者", nickName);
            map.put("日期时间", DateUtil.parseDateToStr(DateUtil.DFY_MD_HMS, info.getCreateTime()));
            list.add(map);
        }
        try {
            FileUtil.downloadExcel(list, response, "知识文档资产报表",
                "知识文档资产报表\n" +
//                    "(目录名称)\n" +
                    "编制人:" + user.getNickname() + "                       编制日期:" + DateUtil.getTimeMd());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 文件:文件库文件的分类分析查询
     * @param query
     * @return
     */
    @GetMapping("/classify/queryAll")
//    @Log("文件:文件库文件的分类分析查询")
//    @ApiOperation("文件:文件库文件的分类分析查询")
    public R queryAllClassify(@Validated PortalQueryParam query) {
        //参数验证
        validation(query);
        JSONObject jsonObject = JSONObject.parseObject("{\"state\":\"true\",\"data\":[{\"name\":\"Office\",\"state\":\"true\",\"data\":[\"doc\",\"docx\",\"xls\",\"xlsx\",\"ppt\",\"pptx\"]},{\"name\":\"Flash\",\"state\":\"true\",\"data\":[\"swf\"]},{\"name\":\"PDF\",\"state\":\"true\",\"data\":[\"pdf\"]},{\"name\":\"HTML\",\"state\":\"true\",\"data\":[\"html\",\"js\",\"css\",\"htm\"]},{\"name\":\"audio\",\"state\":\"true\",\"data\":[\"mp3\",\"wma\"]},{\"name\":\"video\",\"state\":\"true\",\"data\":[\"mp4\",\"flv\",\"f4v\",\"mov\"]},{\"name\":\"image\",\"state\":\"true\",\"data\":[\"jpg\",\"jpeg\",\"png\",\"bmp\",\"ico\",\"gif\"]},{\"name\":\"text\",\"state\":\"true\",\"data\":[\"sql\",\"txt\",\"js\",\"java\",\"conf\",\"ini\"]},{\"name\":\"CAD\",\"state\":\"true\",\"data\":[\"dwf\"]},{\"name\":\"zip\",\"state\":\"true\",\"data\":[\"zip\",\"rar\"]}]}");
        JSONArray dataArray = jsonObject.getJSONArray("data");
        Map<String, List<String>> resultMap = new HashMap<>();
        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject dataObject = dataArray.getJSONObject(i);
            String name = dataObject.getString("name");
            List<String> dataList = dataObject.getJSONArray("data").toJavaList(String.class);
            resultMap.put(name, dataList);
        }
        //新的查询方法
        List<FileAnalysisDataVo> newFileAnalysisData = searchFilesInfoFactory.getNewFileAnalysisData(resultMap, query.getLibraryType());
//
//        List<FileFormatSuffixDto> fileFormatInfo = searchFilesInfoFactory.getFileFormatInfo(query.getLibraryType());
//        List<FilesTree> filesTrees = searchFilesInfoFactory.queryNodeFileInfo(query, FileUserUtils.getUser());
//        List<FileAnalysisInfo> infos = FileAnalysisUtils.fileAnalysisData(filesTrees, fileFormatInfo);
//        return BaseRespResult.successResult(infos);
        return R.ok(newFileAnalysisData);
    }






    private void validation(PortalQueryParam query) {
        Date startDate = query.getStartDate();
        Date endDate = query.getEndDate();
        // 判断这两个日期要么都为空，要么都有值
        if ((startDate == null && endDate != null) || (startDate != null && endDate == null)) {
            throw new IllegalArgumentException("开始日期和结束日期必须同时存在或同时不存在。");
        }
    }
}
